<?php

namespace Packages\Upload\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use OSS\Core\OssException;
use OSS\OssClient;

class UploadController extends Controller
{
    private $ossClient;

    private $bucket;

    private $ossUrl;

    public function __construct()
    {
        // 配置信息
        $this->bucket = env('ALIOSS_BUCKET');
        $this->ossUrl = 'https://' . env('ALIOSS_BUCKET') . '.' . env('ALIOSS_END_POINT');
        // 初始化
        $this->ossClient = new OssClient(env('ALIOSS_ACCESS_KEY_ID'), env('ALIOSS_ACCESS_KEY_SECRET'), env('ALIOSS_END_POINT'));
    }

    /**
     * 获取alioss上传凭证
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAliOSSPolicy(Request $request)
    {
        // 定义业务参数验证规则 验证参数
        $params = $this->validateParams($request, [
            'file_dir' => 'string|max:32',
        ]);

        $file_dir = $params['file_dir'] ?? 'default';

        $res = app('uploadService')->genPolicy($file_dir);

        return $this->returnResponse($res);
    }

    /**
     * 验证图片是否合法
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkImage(Request $request)
    {

        $res = app('wxService')->checkImage($request);

        if ($res['status']) {
            return response()->json(['serverTime' => time(), 'ServerNo' => 200, 'ResultData' => $res['msg']]);
        } else {
            return response()->json(['serverTime' => time(), 'ServerNo' => 400, 'ResultData' => $res['msg']]);
        }
    }

    /**
     * alioss回调
     *
     * @param Request $request
     */
    public function notify(Request $request)
    {
        app('uploadService')->callback($request);
    }
}
